const app = getApp()
let utils = require('../../utils/util.js')

Page({
  data: {
    groupId: '',
    itemId: '',
    scrollHeight: 0,        //"滚动视图的高度"
    topIcon: '',
    detailImg: '',
    completeNum: 0, //已团购数量
    groupendNum: 0,  //成团人数
    groupendNumWord: '',  //成团人数大写
    goodName: "",          //商品名称
    recipe: "",     //配方
    price: 0,          //原价
    groupPrice: 0,       //团购价
    existingList: [],
    intervalId: -1000,      //刷新现成团计时器id
    pollInterval: 5,         //轮询间隔的时间
    pollConut: 0,            //轮询计时
    animationData: {},
    animation: null,
    homeStatus: 'out',
  },
  requestData() {
    //现成团数据
    // this.setData({
    //   existingList: [{ groupId: "1", icon: '../../images/headIcon.jpg', name: '午夜屠蚊男', leftNum: 1, seconds: 123145 },
    //   { groupId: "2", icon: '../../images/headIcon.jpg', name: '午夜屠蚊男', leftNum: 1, seconds: 123145 }]
    // }, this.addInterval);
    //this.refreshExistingTime();
    app.post('goods/item/info', {groupId: this.data.groupId}, this, this.requestData, []).then((res) => {
      let resultObj = res.data.data
      this.data.itemId = resultObj.itemId
      this.setData({
        'completeNum': resultObj.groupendNum,
        'groupendNum': resultObj.groupNum,
        'goodName': resultObj.itemName,
        'price': resultObj.price,
        'groupPrice': resultObj.groupPrice,
        'recipe': resultObj.itemSuggest,
        'topIcon': resultObj.itemImage,
        'detailImg': resultObj.detailImage,
        "groupendNumWord": utils.convertChinese(resultObj.groupNum)
      }, () => {
        app.toggleLoading(false)
      })
    }).catch((errMsg) => {
      console.log(errMsg)    //错误提示信息
    })
  },
  onLoad(options) {
    console.log('open界面收到的参数=' + options.id)
    app.toggleLoading(true)
    this.data.groupId = options.id
    this.requestData()
    //创建动画
    var animation = wx.createAnimation({
      timingFunction: 'ease-in-out',
    })
    this.animation = animation
  },
  onReady() {
    var query = wx.createSelectorQuery()
    query.select('#open-bottom').boundingClientRect()
    wx.getSystemInfo({
      success: win_res => {
        //获取滚动条的高度
        query.exec(dom_res => {
          if (!dom_res[0]) this.setData({scrollHeight: win_res.windowHeight})
          else {
            let bottom_h = dom_res[0].height
            this.setData({scrollHeight: win_res.windowHeight - bottom_h})
          }
        })
      }
    })
  },
  onHide: function () {
    console.log('index---------onHide()')
  },
  /**
   * 当页面销毁时调用
   */
  onUnload: function () {
    console.log('index---------onUnload')
  },
  openBtnClickHandle(e) {
    console.log("点击了开团按钮")
    app.toggleLoading(true)

    app.post('user/order/create', {
      groupId: this.data.groupId
    }).then((res) => {
      let resultObj = res.data.data
      app.toggleLoading(false)
      if (!res.data.success) {
        let statusCode = res.data.code.toString()
        if (statusCode === '10001') {
          wx.showToast({title: '该团购已过期', icon: 'none'})
        }
        else if (statusCode === '10002') {
          wx.showToast({title: '该团购已过期', icon: 'none'})
        }
        else if (statusCode === '10003') {
          wx.showToast({title: '团购已完成', icon: 'none'})
        }
        else if (statusCode === '10004') {
          wx.showToast({title: '团购失败，请重试!', icon: 'none'})
        }
        else if (statusCode === '10005') {
          wx.showToast({title: '团购失败，请重试!', icon: 'none'})
        }
        else if (statusCode === '10006') {
          wx.showToast({title: '团购已完成', icon: 'none'})
        }
        else if (statusCode === '10007') {
          wx.showToast({title: '您的余额不足', icon: 'none'})
        }
        else if (statusCode === '10008') {
          wx.showToast({title: '订单已支付', icon: 'none'})
        }
        else if (statusCode === '10009') {
          wx.showToast({title: '当前订单已关闭', icon: 'none'})
        }
        else if (statusCode === '10010') {
          wx.showToast({title: '您参与的团购已达上限', icon: 'none'})
        }
        else if (statusCode === '10011') {
          wx.showToast({title: '支付失败，无效支付', icon: 'none'})
        }
        else if (statusCode === '10022') {
          wx.showToast({title: '您已经团购过该商品', icon: 'none'})
        }
        return
      }

      let groupNo = resultObj.groupNo
      let newOrder = {'orderId': resultObj.orderNo}
      app.globalData.newOrders.push(newOrder)
      //生成了新的订单;
      console.log(newOrder)
      wx.requestPayment({
        timeStamp: resultObj.timeStamp,        //随机字符串，长度为32个字符以下。
        nonceStr: resultObj.nonceStr,         //统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=*
        package: resultObj.package,      //签名算法，暂支持 MD5 signType: 'MD5',
        signType: 'MD5',
        paySign: resultObj.paySign,
        success: res => {
          console.log('支付成功')
          app.globalData.shareImg = this.data.topIcon
          wx.redirectTo({url: `../payok/payok?id=${groupNo}`})
        },
        fail: res => {
          console.log(res)
          // wx.showToast({ title: '支付失败', icon: 'none' });
        },
        complete: res => {
        }
      })
    }).catch((errMsg) => {
      console.log(errMsg)    //错误提示信息
      app.toggleLoading(false)
    })
  },
  refreshExistingTime() {           //刷新现成团的时间
    if (!this.data.existingList || this.data.existingList.length === 0) return
    let tempExistingList = this.data.existingList
    let len = this.data.existingList.length
    for (let i = len - 1; i >= 0; i--) {
      let existingItem = tempExistingList[i]
      existingItem.seconds--
      if (existingItem.seconds <= 0) {
        tempExistingList.splice(i, 1)
        continue
      }
      existingItem["leftTime"] = utils.secToTime(existingItem.seconds)
    }
    this.setData({existingList: tempExistingList})
  },
  addInterval() {                           //添加计时器
    if (this.data.intervalId !== -1000) return
    this.data.pollConut = 0
    this.data.intervalId = setInterval(this.intervalHandle, 1000)
  },
  intervalHandle() {                        //计时器处理
    this.refreshExistingTime()
    this.data.pollConut++
    if (this.data.pollConut >= this.data.pollInterval) {
      this.data.pollConut = 0
      this.pollExistingGroup()
    }
  },
  removeInterval() {                     //移除计时器
    if (this.data.intervalId === -1000) return
    clearInterval(this.data.intervalId)
    this.data.intervalId = -1000
  },
  pollExistingGroup() {                      //轮询现成团处理
    console.log("请求轮询刷新现成团数据....")
  },
  toIndex() {
    wx.switchTab({url: '../index/index'})
  },
  scrollHandle(e) {
    if (e.detail.scrollTop <= 0) {
      this.slideHomeOut()
      return
    }
    if (this.data.scrollHeight + e.detail.scrollTop >= e.detail.scrollHeight) {
      this.slideHomeIn()
      return
    }
    if (e.detail.deltaY < 0) {                   //向上滚动
      this.slideHomeIn()
    }
    else {
      this.slideHomeOut()
    }
  },
  onShareAppMessage(options) {
    var shareObj = {
      title: "限时团购,等你加入~"
    }
    shareObj.path = '/pages/index/index'
    //shareObj.imageUrl = this.data.topIcon
    return shareObj
  },
  slideHomeOut() {
    if (this.homeStatus === 'out') return
    this.homeStatus = 'out'
    this.animation.opacity(1).left('620rpx').step({duration: 1000})
    this.setData({animationData: this.animation.export()})
  },
  slideHomeIn() {
    if (this.homeStatus === 'in') return
    this.homeStatus = 'in'
    this.animation.opacity(0).left('900rpx').step({duration: 650})
    this.setData({animationData: this.animation.export()})
  }
})

